import { http } from "@/utils/http";
import type { ApiResponse } from "../user";

export interface OrgContactPayload {
  contact_name?: string;
  contact_phone?: string;
  contact_email?: string;
  bank_name?: string;
  bank_account?: string;
  bank_account_name?: string;
  invoice_title?: string;
  invoice_taxno?: string;
}

export interface OrgAddressPayload {
  id?: number | null;
  contact_name?: string;
  contact_phone?: string;
  province?: string;
  city?: string;
  district?: string;
  address?: string;
  postal_code?: string;
  is_default?: number | boolean;
  address_type?: string;
}

export interface OrgSettings {
  id: number;
  name: string;
  org_type: string;
  status: number;
  member_role: string;
  contact: OrgContactPayload;
  shipping_address?: OrgAddressPayload;
  receiving_address?: OrgAddressPayload;
}

export interface UserProfileInfo {
  id: number;
  phone: string;
  email?: string | null;
  status: number;
  nickname: string;
  real_name?: string | null;
  avatar?: string | null;
}

export interface UserProfileResult {
  profile: UserProfileInfo;
  roles: Array<Record<string, any>>;
  identities: Array<Record<string, any>>;
  orgs: Array<OrgSettings>;
}

export interface UpdateProfilePayload {
  nickname?: string;
  real_name?: string;
  email?: string;
  avatar?: string;
}

export interface UpdatePasswordPayload {
  current_password: string;
  new_password: string;
  confirm_password: string;
}

export interface UpdateOrgPayload {
  contact?: OrgContactPayload;
  shipping_address?: OrgAddressPayload;
  receiving_address?: OrgAddressPayload;
}

export const fetchUserProfile = () => {
  return http.request<ApiResponse<UserProfileResult>>("get", "/user/profile");
};

export const updateUserProfile = (data: UpdateProfilePayload) => {
  return http.request<ApiResponse<UserProfileResult>>("put", "/user/profile", {
    data
  });
};

export const updateUserPassword = (data: UpdatePasswordPayload) => {
  return http.request<ApiResponse<boolean>>("put", "/user/profile/password", {
    data
  });
};

export const updateOrgSettings = (orgId: number, data: UpdateOrgPayload) => {
  return http.request<ApiResponse<{ org: OrgSettings }>>(
    "put",
    `/user/org/${orgId}/settings`,
    { data }
  );
};
